package com.snow.controller.admin;

import com.github.pagehelper.PageInfo;
import com.snow.constant.Types;
import com.snow.constant.Webconst;
import com.snow.controller.BaseController;
import com.snow.exception.SiteException;
import com.snow.pojo.dto.cond.ContentCond;
import com.snow.pojo.dto.cond.MetaCond;
import com.snow.pojo.model.ContentDomain;
import com.snow.pojo.model.MetaDomain;
import com.snow.pojo.model.UserDomain;
import com.snow.qiniu.QiniuService;
import com.snow.service.content.ContentService;
import com.snow.service.log.LogService;
import com.snow.service.meta.MetaService;
import com.snow.utils.AdminCommons;
import com.snow.utils.ApiResponse;
import com.snow.utils.Commons;
import com.snow.utils.TaleUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.security.auth.Subject;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Description:
 * @author: snow
 * @Date: 2020-01-28
 **/
@Api("文章管理页")
@RequestMapping("admin/article")
@Transactional(rollbackFor = SiteException.class)
@Controller
public class ArticleController extends BaseController {
    private static Logger log = LoggerFactory.getLogger(ArticleController.class);
    @Autowired
    private MetaService metaService;
    @Autowired
    private Commons commons;
    @Autowired
    private ContentService contentService;
    @Autowired
    private AdminCommons adminCommons;
    @Autowired
    private LogService logService;
    @Autowired
    private QiniuService qiniuService;
    @Value("${qiniu.cdn.url}")
    private String QINIU_URL;
    @ApiOperation("进入文章管理页")
    @GetMapping("")
    public String index(
            Model model,
            @ApiParam(name="page",value = "页数",required = false)
            @RequestParam(name="page",required = false,defaultValue = "1")
                    int page,
            @ApiParam(name="limit",value="每页数量",required = false)
            @RequestParam(name="limit",required = false,defaultValue = "15")
                    int limit
    ){
        PageInfo<ContentDomain> articles = contentService.getArticlesByCond(new ContentCond(), page, limit);
        log.debug("articles size is =====>"+articles.getSize());
        model.addAttribute("articles",articles);
        model.addAttribute("commons",commons);
        return "admin/article_list";
    }
    @GetMapping("/publish")
    public String publishPage(Model model){
        MetaCond metaCond = new MetaCond();
        metaCond.setType(Types.CATEGORY.getType());
        List<MetaDomain> metas = metaService.getMetasByCond(metaCond);
        model.addAttribute("categories",metas);
        model.addAttribute("commons",commons);
        model.addAttribute("adminCommons", adminCommons);
        return "admin/article_edit";
    }

    /**
     * 处理点击文章列表页的编辑按钮
     * @param cid
     * @param model
     * @return
     */
    @ApiOperation("文章编辑")
    @GetMapping(value="/{cid}")
    public String editPage(
            @ApiParam(name="cid",value="文章编号",required = true)
            @PathVariable Integer cid,Model model){
        ContentDomain content = contentService.getArticleById(cid);
        MetaCond metaCond = new MetaCond();
        metaCond.setType(Types.CATEGORY.getType());
        List<MetaDomain> metas = metaService.getMetasByCond(metaCond);
        model.addAttribute("contents",content);
        model.addAttribute("categories",metas);
        model.addAttribute("active","article");
        model.addAttribute("commons",commons);
        model.addAttribute("adminCommons",adminCommons);
        return "admin/article_edit";

    }
    @ApiOperation("发布文章")
    @PostMapping("/publish")
    @ResponseBody
    //@RequestParam：将请求参数绑定到你控制器的方法参数上（是springmvc中接收普通参数的注解）
    public ApiResponse publishArticle(
            @ApiParam(name="title",value="标题",required = true)
            @RequestParam(name="title",required = true)
            String title,
            @ApiParam(name="titlePic",value="标题图片",required = false)
            @RequestParam(name="titlePic",required = false)
            String titlePic,
            @ApiParam(name="slug",value="内容缩略名",required = false)
            @RequestParam(name="slug",required = false)
            String slug,
            @ApiParam(name="content",value="博客内容",required = true)
            @RequestParam(name="content",required = true)
            String content,
            @ApiParam(name="type",value="文章内容",required = true)
            @RequestParam(name="type",required = true)
            String type,
            @ApiParam(name="status",value="文章状态",required = true)
            @RequestParam(name="status",required = true)
            String status,
            @ApiParam(name="categories",value="分类",required = true)
            @RequestParam(name="categories",required = true)
            String categories,
            @ApiParam(name="tags",value="标签",required = false)
            @RequestParam(name="tags",required = false)
            String tags,
            @ApiParam(name="allowComment",value="是否允许评论",required = true)
            @RequestParam(name="allowComment",required = true)
            Boolean allowComment
        ){

        log.info("======> Add Article ");
        ContentDomain domain = new ContentDomain();
        domain.setTitle(title);
        domain.setTitlePic(titlePic);
        domain.setCategories(categories.equals(Types.CATEGORY.getType())?categories : null);
        domain.setTags(tags.equals(Types.TAG.getType())?type:null);
        domain.setType(type);
        domain.setAllowComment(allowComment? 1 : 0);
        domain.setContent(content);
        domain.setStatus(status);
        domain.setSlug(slug);
        //把content的第一张照片设置为TitlePic,上传到七牛云，并把url保存到TitlePic
//        String localPicPath = Commons.show_thumb(content);
//        String fkey = qiniuService.uploadLocalFile(localPicPath);
//        fkey = QINIU_URL + fkey;
//        domain.setTitlePic(fkey);
        contentService.addArticle(domain);
        log.info("======>add successful");
        return ApiResponse.success();

    }
    @ApiOperation("删除博客")
    @ResponseBody
    @PostMapping("/delete")
    public ApiResponse deleteArticle(
            @ApiParam(name="cid",value = "文章主键标号",required = true)
            @RequestParam(name="cid",required = true)
            Integer cid, HttpServletRequest request
            ){
            contentService.deleteArticleById(cid);
            logService.addLog("Delete Artice with id" + cid ,"" + cid,request.getRemoteAddr(), 1);
            return ApiResponse.success();
    }
    @ApiOperation("文章修改")
    @PostMapping("/modify")
    @ResponseBody
    public ApiResponse modify(
            Model model,
            @ApiParam(name="cid",value = "修改的文章主键",required = true)
            @RequestParam(name="cid",required = true)
            Integer cid,
            @ApiParam(name="title",value="标题",required = true)
            @RequestParam(name="title",required = true)
                    String title,
            @ApiParam(name="titlePic",value="标题图片",required = false)
            @RequestParam(name="titlePic",required = false)
                    String titlePic,
            @ApiParam(name="slug",value="内容缩略名",required = false)
            @RequestParam(name="slug",required = false)
                    String slug,
            @ApiParam(name="content",value="博客内容",required = true)
            @RequestParam(name="content",required = true)
                    String content,
            @ApiParam(name="type",value="文章内容",required = true)
            @RequestParam(name="type",required = true)
                    String type,
            @ApiParam(name="status",value="文章状态",required = true)
            @RequestParam(name="status",required = true)
                    String status,
            @ApiParam(name="categories",value="分类",required = true)
            @RequestParam(name="categories",required = true)
                    String categories,
            @ApiParam(name="tags",value="标签",required = false)
            @RequestParam(name="tags",required = false)
                    String tags,
            @ApiParam(name="allowComment",value="是否允许评论",required = true)
            @RequestParam(name="allowComment",required = true)
                    Boolean allowComment
    ){
        ContentDomain contentDomain = new ContentDomain();
        contentDomain.setCid(cid);
        contentDomain.setTitle(title);
        contentDomain.setTitlePic(titlePic);
        contentDomain.setContent(content);
        contentDomain.setSlug(slug);
        contentDomain.setStatus(status);
        contentDomain.setType(type);
        contentDomain.setCategories(categories.equals(Types.CATEGORY.getType())?categories : null);
        contentDomain.setTags(tags.equals(Types.TAG.getType())?tags : null);
        contentDomain.setAllowComment(allowComment? 1 : 0);
        contentService.updateContentById(contentDomain);
        return ApiResponse.success();
    }

}
